//请求用
var dict_request = {};
//编辑用
var editmodel = [];
//表格用
var tablelist = [];

$.ajax({
	url: 'http://' + ipm + ':8081/dict/query',
	type: 'POST',
	contentType: 'application/json',
	dataType: 'json',
	data: {},
	success: function (response) {
		console.log(response);
		dictRead(response);
	}
});

function refreshTab() {
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/query',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: {},
		success: function (response) {
			console.log(response);
			tablelist = [];
			dict_request = {};
			console.log(dict_request);
			dictRead(response);
			console.log(tablelist);
			console.log(dict_request);
		}
	});
}


function createTab() {
	$("#table_page").bootstrapTable('destroy').bootstrapTable({
		//url: '',
		data: tablelist,
		dataType: 'json',
		//method: 'POST',                      //请求方式（*）
		//toolbar: '#toolbar',              //工具按钮用哪个容器
		striped: true,                      //是否显示行间隔色
		cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		pagination: true,                   //是否显示分页（*）
		sortable: true,                     //是否启用排序
		sortOrder: "asc",                   //排序方式
		sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
		pageNumber: 1,                      //初始化加载第一页，默认第一页,并记录
		pageSize: 10,                     //每页的记录行数（*）
		pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
		search: false,                      //是否显示表格搜索
		strictSearch: true,
		//showColumns: true,                  //是否显示所有的列（选择显示的列）
		//showRefresh: true,                  //是否显示刷新按钮
		minimumCountColumns: 1,             //最少允许的列数
		clickToSelect: true,                //是否启用点击选中行
		//height: 500,                      //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
		uniqueId: "name",                     //每一行的唯一标识，一般为主键列
		//showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
		cardView: false,                    //是否显示详细视图
		detailView: false,                  //是否显示父子表
		//得到查询的参数
		queryParams: function (params) {
			//这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
			var temp = {
				rows: params.limit,                         //页面大小
				page: (params.offset / params.limit) + 1,   //页码
				sort: params.sort,      //排序列名  
				sortOrder: params.order //排位命令（desc，asc） 
			};
			return temp;
		},

		columns: [{
			field: 'name',
			title: '字典名'
		}, {
			field: 'inserttime',
			title: '插入时间'
		}, {
			field: 'updatetime',
			title: '更新时间'
		}, {
			field: 'ID',
			title: '编辑',
			width: 120,
			align: 'center',
			valign: 'middle',
			formatter: actionFormatter
		}, {
			field: 'name',
			title: '删除',
			width: 120,
			align: 'center',
			valign: 'middle',
			formatter: actionFormatterD
		},
		],
		onLoadSuccess: function () {
		},
		onLoadError: function () {
			showTips("数据加载失败！");
		},
		onDblClickRow: function (row, $element) {
			var id = row.ID;
			EditViewById(id, 'view');
		},

	});


}

function actionFormatter(value, row, index) {
	var id = value;
	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs blue' onclick=\"EditViewById('" + id + "')\" title='编辑'><span class='feather-edit'></span></a>";

	return result;
}
function actionFormatterD(value, row, index) {
	var id = value;

	var result = "";
	result += "<a href='javascript:;' class='btn btn-xs red' onclick=\"dictionary_modify('" + id + "')\" title='删除'><span class='feather-trash-2'></span></a>";

	return result;
}

//新增模态框清理
$('#dictModal').on('hidden.bs.modal', function () {
	deletedictViewAdd();
});

function deletedictViewAdd() {
	var Table = document.getElementById("tableroom");

	let tbody = Table.tBodies[0];

	// 循环删除 tbody 的所有行
	while (tbody.rows.length > 0) {
		tbody.deleteRow(0);
	}

}


//编辑模态框清理
$('#myModal').on('hidden.bs.modal', function () {
	deletedictViewEdit();
});

function deletedictViewEdit() {
	var Table = document.getElementById("dictView");
	var rows = Table.getElementsByTagName("tr").length;
	var rowsNum = 0;
	for (rowsNum; rowsNum < rows - 1; rowsNum++) {
		NewRow = Table.deleteRow(-1); //添加
	}
}


//新增字典模态框构建
function createDictModel() {
	$('#dictModal').modal('show');

}

var dictnameroom
//根据ID编辑对应内容
function EditViewById(args) {
	$('#myModal').modal('show');
	var Table = document.getElementById("dictView");
	console.log(dict_request);
	currentId = args - 1;
	var dictA = dict_request.dict;
	dictnameroom = dictA[args - 1].name;
	var rowsNum = 0;
	console.log(args);

	//for (rowsNum; rowsNum < editmodel[args].length; rowsNum++) {

	for (rowsNum; rowsNum < editmodel[args - 1].length; rowsNum++) {
		NewRow = Table.insertRow(); //添加行
		//添加列
		key = NewRow.insertCell();
		value = NewRow.insertCell();
		unit = NewRow.insertCell();
		operate = NewRow.insertCell();
		//属性赋值
		key.innerHTML = "<input id = key" + rowsNum + 1 + " Name=key" + rowsNum + 1 + " value=" + editmodel[args - 1][rowsNum].key + " class='form-control form-control-sm' type='number' />";
		value.innerHTML = "<input id = value" + rowsNum + 1 + " Name=value" + rowsNum + 1 + " value=" + editmodel[args - 1][rowsNum].value + " class='form-control form-control-sm' type='text' />";
		unit.innerHTML = "<input id = unit" + rowsNum + 1 + " Name=unit" + rowsNum + 1 + "  placeholder='未定义' class='form-control form-control-sm' type='text'  value=" + editmodel[args - 1][rowsNum].unit + ">";
		operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceDictParam(' + (args - 1) + ');">删除</a></div>';
	}
}

//ID编辑插入一行
function addEditViewTable() {
	var Table = document.getElementById("dictView");

	var rowsNum = Table.rows.length - 1;
	NewRow = Table.insertRow(); //添加行
	//添加列
	key = NewRow.insertCell();
	value = NewRow.insertCell();
	unit = NewRow.insertCell();
	operate = NewRow.insertCell();

	//属性赋值

	key.innerHTML = "<input id = key" + rowsNum + 1 + " Name=key" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	value.innerHTML = "<input id = value" + rowsNum + 1 + " Name=value" + rowsNum + 1 + " class='form-control form-control-sm'  type='text' />";
	unit.innerHTML = "<input id = unit" + rowsNum + 1 + " Name=unit" + rowsNum + 1 + " placeholder='未定义' class='form-control form-control-sm'  type='text' />";
	operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceDictParam();">删除</a></div>';

}

//删除编辑中的字典字段
function deleteInterfaceDictParam() {
	var td = event.srcElement; // 通过event.srcElement 获取激活事件的对象 td
	var key = td.parentElement.parentElement.parentNode.rowIndex;  //获取行索引
	document.getElementById("dictView").deleteRow(key); //删除
}


//增加一个字典
var tableN = 0;
function addDictTable() {
	var Tableroom = document.getElementById("tableroom");
	var tableNum = Tableroom.rows.length - 1;
	NewRow = Tableroom.insertRow(); //添加行
	room = NewRow.insertCell();
	room.innerHTML = '<div class="row"><div class="col-12"><div class="card"><div class="card-body"><div class="form-group row mb-3"><label for=dict' + (tableNum + 1) + ' class="col-3 col-form-label">字典名：</label><div class="col-9"><input type="text" class="form-control" id=dict' + (tableNum + 1) + ' name=dict' + (tableNum + 1) + ' value=dict' + (tableNum + 1) + '></div></div><table  class="table-1" id = dictionary' + (tableNum + 1) + ' ><tr><td style="width: 160px;" align = "center" >键</td><td style="width: 160px;" align = "center" >值</td><td style="width: 80px;" align = "center" >单位</td><td style="width: 60px;" align = "center">操作</td></tr></table><div><a  href="javascript:;" onclick="addDictionary(' + (tableNum + 1) + ')" title="添加"><span  class="feather-plus-circle"></span></a></div></div></div></div>';
	tableN++;
}


//增加一个待编辑字典字段
function addDictionary(args) {
	var Table = document.getElementById("dictionary" + args);

	var rowsNum = Table.rows.length - 1;
	NewRow = Table.insertRow(); //添加行
	//添加列
	key = NewRow.insertCell();
	value = NewRow.insertCell();
	unit = NewRow.insertCell();
	operate = NewRow.insertCell();

	//属性赋值

	key.innerHTML = "<input id = key" + (rowsNum + 1) + " Name=key" + (rowsNum + 1) + " class='form-control form-control-sm'  type='number' />";
	value.innerHTML = "<input id = value" + (rowsNum + 1) + " Name=value" + (rowsNum + 1) + "  class='form-control form-control-sm'  type='text' />";
	unit.innerHTML = "<input id = unit" + (rowsNum + 1) + " Name=unit" + (rowsNum + 1) + " placeholder='未定义' class='form-control form-control-sm'  type='text' />";
	operate.innerHTML = '<div id=operate' + (rowsNum + 1) + '><a style="cursor:pointer;color:#007bff;"  onclick="deleteInterfaceParam(' + args + ');">删除</a></div>';

}

//验证是否有空信息
function checkDict(args) {
	for (var i = 0; i < args.length; i++) {
		var id = document.getElementById(args[i].name).value;
		var name = document.getElementById(args[i].name).name;
		console.log(name.search("unit"))

		if (id.length == 0) {
			if(name.search("unit") == 0){
				continue;
			}else{
				alert('输入不能为空');
				return false;
			}
		}

	}

}


//删除编辑中的字典字段
function deleteInterfaceParam(args) {
	var td = event.srcElement; // 通过event.srcElement 获取激活事件的对象 td
	var key = td.parentElement.parentElement.parentNode.rowIndex;  //获取行索引
	document.getElementById("dictionary" + args).deleteRow(key); //删除
}




//增加/插入一个字典JSON
function buildDictJson() {
	var register = $("#dictForm");
	var formData = register.serializeArray();
	if (checkDict(formData) == false) {
		return false;
	}

	var arrDict = dict_request.dict;

	if (arrDict) {//如果有数据
		for (var i = 0; i < arrDict.length; i++) {
			for (var j = 0; j < formData.length; j++) {
				if (arrDict[i].name == formData[j].value) {
					alert("请勿重复输入相同的字典");
					return false;
				}
			}
		}
		var dictWeb = {
			"cfgType": "1",
			// "cfgName": "",
			"cfgName": "dict_cfg.json",
			"content": "",
			// "syncNodes": ""
		}
		var dictSave = {
			"cfg_type": 1,
			"dict": ""
		}
		var dictA = {
			"name": "xxxx",
			"context": "xxxx"
		}
		var json = []
		var j = 1;
		dictA.name = formData[0].value;
		for (var i = 1; i < formData.length; i++) {
			var obj = {}
			if (formData[i].name == "dict" + j) {
				dictA.context = json;
				arrDict.push(dictA);
				json = []
				var dictA = {
					"name": "xxxx",
					"context": "xxxx"
				}
				dictA.name = formData[i].value;
				j++;
				i++;
			}
			formData[i].name = "key";
			formData[i + 1].name = "value";
			formData[i + 2].name = "unit";
			obj[formData[i].name] = parseInt(formData[i]['value']);
			obj[formData[i + 1].name] = formData[i + 1]['value'];
			obj[formData[i + 2].name] = formData[i + 2]['value'];
			json.push(obj);
			i = i + 2;
		}
		dictA.context = json;
		arrDict.push(dictA);
		dictSave.dict = arrDict;
		dictWeb.content = JSON.stringify(dictSave)
		postQuestSave(dictWeb);
		alert("新增成功！");
		//refreshTab();
		window.location.reload();
	} else {//如果没有数据
		arrDict = []
		var dictWeb = {
			"cfgType": "1",
			// "cfgName": "",
			"cfgName": "dict_cfg.json",
			"content": "",
			// "syncNodes": ""
		}
		var dictSave = {
			"cfg_type": 1,
			"dict": ""
		}
		var dictA = {
			"name": "xxxx",
			"context": "xxxx"
		}
		var json = []
		var j = 1;
		dictA.name = formData[0].value;
		for (var i = 1; i < formData.length; i++) {
			var obj = {}
			if (formData[i].name == "dict" + j) {
				dictA.context = json;
				arrDict.push(dictA);
				json = []
				var dictA = {
					"name": "xxxx",
					"context": "xxxx"
				}
				dictA.name = formData[i].value;
				j++;
				i++;
			}
			formData[i].name = "key";
			formData[i + 1].name = "value";
			formData[i + 2].name = "unit";
			obj[formData[i].name] = parseInt(formData[i]['value']);
			obj[formData[i + 1].name] = formData[i + 1]['value'];
			obj[formData[i + 2].name] = formData[i + 2]['value'];
			json.push(obj);
			i = i + 2;
		}
		dictA.context = json;
		arrDict.push(dictA);
		dictSave.dict = arrDict;
		dictWeb.content = JSON.stringify(dictSave)
		postQuestSave(dictWeb);
		alert("新增成功！");
		//refreshTab();
		window.location.reload();
	}

}


//删除字典JSON
function dictionary_modify(args) {
	// 	var arrDict = dict_request.dict;
	// 	if (arrDict.length < 2) {
	// 		alert('请勿全部删除');
	// 		return false;
	// 	}
	var arrDict = []
	var dictWeb = {
		"cfgType": 1,
		"deletedName": ""
	}

	// var dictWeb = {
	// 	"cfgType": "1",
	// 	"content": ""
	// }

	// var dictWeb1 = {
	// 	"cfgType":1,
	// 	"deletedName": "",
	// 	"id": 0
	// }
	dictWeb.deletedName = args;
	arrDict.push(dictWeb)
	sss = JSON.stringify(arrDict)
	// console.log(dictWeb)
	// console.log(arrDict)
	// console.log(sss)
	$.ajax({
		url: 'http://' + ipm + ':8081/dict/deleteProto',
		type: 'POST',
		contentType: 'application/json',
		dataType: 'json',
		data: sss,
		success: function (response) {
			console.log(response);
		}
	});
	window.location.reload();
}

// //字典，删除函数
// function DeleteDictByIds(args) {
// 	var arrDict = dict_request.dict;
// 	if (arrDict.length < 2) {
// 		alert('请勿全部删除');
// 		return false;
// 	}
// 	for (var i = 0; i < arrDict.length; i++) {
// 		if (arrDict[i].name == args) {
// 			arrDict.splice(i, 1);
// 		}
// 	}
// 	console.log(arrDict);

// 	var dictWeb = {
// 		"cfgType": "1",
// 		"content": ""
// 	}

// 	var dictSave = {
// 		"cfg_type": 1,
// 		"dict": ""
// 	}

// 	dictSave.dict = arrDict;
// 	dictWeb.content = JSON.stringify(dictSave)
// 	postQuestSave(dictWeb);
// 	//refreshTab();
// 	window.location.reload();

// }



//更新编辑字典JSON
function buildEditDictJson() {

	var register = $("#dictForm1");
	var formData = register.serializeArray();
	//console.log(formData);

	var arrDict = dict_request.dict;
	//console.log(arrDict);
	var dictWeb = {
		"cfgType": "1",
		"cfgName": "dict_cfg.json",
		"content": "",
		// "syncNodes": ""
	}
	var dictSave = {
		"cfg_type": 1,
		"dict": ""
	}
	var json = []
	var arr = []
	for (var i = 0; i < arrDict.length; i++) {
		//console.log(arrDict[i].name);
		if (arrDict[i].name == dictnameroom) {
			for (var j = 0; j < formData.length; j++) {
				var obj = {}
				formData[j].name = "key";
				formData[j + 1].name = "value";
				formData[j + 2].name = "unit";
				obj[formData[j].name] = parseInt(formData[j]['value']);
				obj[formData[j + 1].name] = formData[j + 1]['value'];
				obj[formData[j + 2].name] = formData[j + 2]['value'];
				json.push(obj);
				j = j + 2;
			}
			//console.log(json);
			arrDict[i].context = json;
			arr.push(arrDict[i]);
		} else {
			arr.push(arrDict[i]);
		}
		//console.log(arr);
	}
	dictSave.dict = arr;
	dictWeb.content = JSON.stringify(dictSave)
	//console.log(dictWeb);
	postQuestSave(dictWeb);
	//refreshTab();
	window.location.reload();
	//alert("新增成功！");

}




